package com.geecg.hb.asqlhandle;

import java.lang.reflect.ParameterizedType;
import java.util.Arrays;
import java.util.List;

import com.geecg.hb.bean.ConditionParams;
import com.geecg.hb.dbhandle.HandleDB;

public class SqlHandleImpl<T,E> extends SqlSplitHandle<T> implements SqlMethods<T,E> {
	
	public HandleDB<T> hdb=new HandleDB<T>();
	
	private Class<T> clazz;
//	private T t;
	@SuppressWarnings("unchecked")
	public SqlHandleImpl(){
		ParameterizedType type =(ParameterizedType) this.getClass().getGenericSuperclass();
		try {
			clazz=(Class<T>) type.getActualTypeArguments()[0];
//			t=(T) Class.forName(type.getActualTypeArguments()[0].getTypeName());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 根据ID查询数据
	 * */
	public T findByID(String id) {
		List<T> list=hdb.query(getfindByIDSql(id),clazz);
		if(list!=null&&list.size()>0){
			return list.get(0);
		}
		return null;
	}
	/**
	 * 根据给定实体值
	 * */
	public List<T> findByParams(T t) {
		return hdb.query(getByParamsSql(t),clazz);
	}
	
	/**
	 * 根据提供的参数及查询条件返回查询对象
	 * @param obj
	 * @return
	 */
	public List<T> findByConditionParams(T t,ConditionParams...params){
		List<ConditionParams> list= Arrays.asList(params);
		return hdb.query(getConditionSql(t, list),clazz);
	}
	
	/**
	 * 默认浅度更新
	 * */
	public void update(T t) {
		update(t,true);
	}
	
	/**
	 * 默认浅度更新,当bool为false时深度更新
	 * */
	public void update(T t,boolean bool) {
		hdb.update(getUpdataSql(t,bool));
	}
	
	
	public void delete(T t) {
		// TODO Auto-generated method stub
		hdb.update(getDeleteSql(t));
	}

	public void add(T t) {
		// TODO Auto-generated method stub
		StringBuilder sb=new StringBuilder();
		sb.append(getInsertHandleSql());
		sb.append(" values ");
		sb.append(getInsertValuesSql(t));
		hdb.update(sb.toString());
	}
	
	public void saveAll(List<T> list) {
		// TODO Auto-generated method stub
		StringBuilder sb=new StringBuilder();
		sb.append(getInsertHandleSql());
		sb.append(" values ");
		for (T t : list) {
			sb.append(getInsertValuesSql(t));
			sb.append(",");
		}
		sb.deleteCharAt(sb.length()-1);
		System.out.println(sb.toString());
		hdb.update(sb.toString());
	}
	
	
}
